import {
	Button,
	Collapse,
	Form,
	Input,
	Row,
	Col,
	TreeSelect,
	Switch,
	Checkbox,
	message,
} from 'antd'
import React, {memo, useState, useEffect} from 'react'
import {history, connect} from 'umi'
import {getDeptList} from '@/service/system/dept'
import {addUser, editUser, viewUser} from '@/service/system/user'
import {translateDataToTree} from '@/utils/common/index'
import styles from '@/assets/common/css/page.less'

const {TextArea} = Input
const {Panel} = Collapse

const customizeHeader = (value: string) => (
	<div>
		<div className={styles.tip} />
		{value}
	</div>
)

const userDom = memo((props: any) => {
	const currentMerchantId = props?.user?.currentMerchantId
	const [idData, setIdData] = useState('')
	const [treeData, setTreeData] = useState()
	const [type, setType] = useState<string>()

	const [form] = Form.useForm()
	// 部门列表
	const getDeptFun = () => {
		getDeptList({merchantId: currentMerchantId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setTreeData(list as any)
			}
		})
	}
	const viewUserFun = (userId: string) => {
		viewUser(userId, {merchantId: currentMerchantId}).then((res: any) => {
			if (res?.success) {
				const {status, admin} = res.data
				form.setFieldsValue({
					...res.data,
					status: !!status,
					admin: admin === 1 ? ['check'] : [],
				})
			}
		})
	}

	useEffect(() => {
		if (currentMerchantId) {
			getDeptFun()
		}
	}, [currentMerchantId])

	useEffect(() => {
		const {id, departmentId} = props.location.query
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('add')) {
			setType('add')
			form.setFieldsValue({
				status: 1,
			})
		} else {
			setType('edit')
		}
		if (id) {
			setIdData(id)
			viewUserFun(id)
		} else {
			form.setFieldsValue({
				merchantId: currentMerchantId,
				departmentId,
			})
		}
	}, [])

	// 表单提交
	const submit = async () => {
		const formData = await form.validateFields()
		const admin = formData?.admin?.length > 0 ? 1 : 0
		const status = formData?.status ? 1 : 0
		if (!idData) {
			// 新增用户
			addUser({
				...formData,
				merchantId: currentMerchantId,
				status,
				admin,
			})
				.then((res: any) => {
					if (res?.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		} else {
			editUser(idData, {
				...formData,
				merchantId: currentMerchantId,
				status,
				admin,
			})
				.then((res: any) => {
					if (res?.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
	}

	// 表单验证
	const phoneValidator = (_: any, value: string, callback: () => any) => {
		if (value) {
			const reg =
				/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
			if (reg.test(value)) {
				return callback()
			}
			return Promise.reject(new Error('手机号无效'))
		}
		return Promise.reject(new Error('请输入手机号'))
	}

	return (
		<div className={styles.page}>
			<div className={`${styles.content} ${styles.formDetils}`}>
				<Collapse
					defaultActiveKey={['1']}
					ghost
					expandIconPosition="end">
					<Panel header={customizeHeader('基础信息')} key="1">
						<Form
							name="basic"
							layout="horizontal"
							form={form}
							labelCol={{style: {width: 100}}}
							initialValues={{remember: true}}
							autoComplete="off">
							<Row gutter={12}>
								{type !== 'add' ? (
									<Col sm={{span: 24}}>
										<Form.Item
											label="编号"
											name="id"
											rules={[
												{
													required: true,
													message: '请输入',
												},
											]}>
											<Input
												placeholder="请输入"
												disabled
												maxLength={20}
											/>
										</Form.Item>
									</Col>
								) : null}
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="名称"
										name="name"
										rules={[
											{required: true, message: '请输入'},
											{max: 6},
										]}>
										<Input
											placeholder="请输入"
											disabled={type === 'view'}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="部门"
										name="departmentId"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<TreeSelect
											disabled={type === 'view'}
											showSearch
											treeNodeFilterProp="name"
											style={{width: '100%'}}
											dropdownStyle={{
												maxHeight: 400,
												overflow: 'auto',
											}}
											placeholder="请选择部门"
											allowClear
											fieldNames={{
												label: 'name',
												value: 'id',
											}}
											treeDefaultExpandAll
											treeData={treeData}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="手机"
										name="phone"
										rules={[
											{
												required: true,
												validator: phoneValidator,
											},
										]}>
										<Input
											placeholder="请输入手机号"
											disabled={type === 'view'}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="邮箱"
										name="mail"
										rules={[
											{
												type: 'email',
												message: '填写的邮箱格式有误',
											},
										]}>
										<Input
											placeholder="请输入邮箱"
											disabled={type === 'view'}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="状态"
										name="status"
										valuePropName="checked"
										rules={[
											{
												required: true,
												message: '请选择状态',
											},
										]}>
										<Switch disabled={type === 'view'} />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item label="是否管理员" name="admin">
										<Checkbox.Group>
											<Checkbox
												value="check"
												disabled={type === 'view'}
											/>
										</Checkbox.Group>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="职位名称"
										name="positionName">
										<Input
											placeholder="请输入"
											disabled={type === 'view'}
											maxLength={6}
										/>
									</Form.Item>
								</Col>
								<Col sm={{span: 24}} />
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item label="描述" name="description">
										<TextArea
											disabled={type === 'view'}
											placeholder="请输入( 最多200个字 )"
											maxLength={200}
											autoSize={{minRows: 4, maxRows: 6}}
										/>
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</Panel>
				</Collapse>
				<div className={styles.wrap}>
					{type === 'view' ? (
						''
					) : (
						<Button
							type="primary"
							htmlType="submit"
							onClick={submit}>
							保存
						</Button>
					)}

					<Button
						onClick={(e) => {
							e.stopPropagation()
							history.goBack()
						}}>
						取消
					</Button>
				</div>
			</div>
		</div>
	)
})
export default connect(({user}: any) => ({
	user,
}))(userDom)
